<template>
  <div class="form-container">
    <div class="form-wrapper">
      <Form
        ref="expForm"
        :model="expForm"
        :rules="ruleValidate"
        :label-position="labelPosition"
        :label-width="labelWidth">
          <fieldset class="line-field" ref="baseInfoRef">
            <legend>{{ fieldsetTitle }}</legend>
            <FormItem label="基本信息" class="ivu-form-item-required" v-if="beModifiedItem.some(item => { return ['type', 'planHours'].indexOf(item) > -1 })">
              <Row :gutter="20" type="flex">
                <Col span="2" class="pl-15" v-if="beModifiedItem.indexOf('type') > -1">类型：</Col>
                <Col span="6" v-if="beModifiedItem.indexOf('type') > -1">
                  <FormItem prop="type">
                    <Select :enabledPreventOverflow="enabledPreventOverflow" clearable filterable v-model="expForm.type" placeholder="实验类型">
                      <Option value="验证性">验证性</Option>
                      <Option value="演示性">演示性</Option>
                      <Option value="练习性">练习性</Option>
                      <Option value="创新性">创新性</Option>
                      <Option value="设计性">设计性</Option>
                      <Option value="综合性">综合性</Option>
                      <Option value="其他">其他</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="2" class="pl-15" v-if="beModifiedItem.indexOf('planHours') > -1">学时：</Col>
                <Col span="6" v-if="beModifiedItem.indexOf('planHours') > -1">
                  <FormItem prop="learntime">
                    <InputNumber :min="1" v-model="expForm.learntime" style="width: 100%" placeholder="计划学时"></InputNumber>
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
            <FormItem label="项目名称" prop="title" v-if="beModifiedItem.indexOf('title') > -1">
                <Input v-model="expForm.title" clearable placeholder="请输入实验项目名称"></Input>
            </FormItem>
            <FormItem label="耗材需求" prop="resources" v-if="beModifiedItem.indexOf('resources') > -1">
                <Input type="textarea" v-model="expForm.resources" clearable placeholder="本次实验的耗材需求"></Input>
            </FormItem>
            <FormItem label="系统需求" prop="system" v-if="beModifiedItem.indexOf('system') > -1">
                <Input type="textarea" v-model="expForm.system" clearable placeholder="本次实验的系统需求"></Input>
            </FormItem>
            <FormItem label="软件需求" prop="software" v-if="beModifiedItem.indexOf('software') > -1">
                <Input type="textarea" v-model="expForm.software" clearable placeholder="本次实验的软件需求"></Input>
            </FormItem>
            <FormItem
                label="时间及实验室"
                v-for="(timeItem, expTimeIndex) in expForm.expTimeItems"
                :key="timeItem.guid"
                class="ivu-form-item-required ivu-divider-dashed"
                v-if="beModifiedItem.some(item => { return ['sweek', 'sdate', 'section', 'classroom'].indexOf(item) > -1 })">
              <Row :gutter="20" type="flex">
                <Col span="2" class="pl-15 mb-20" v-if="beModifiedItem.indexOf('sweek') > -1">周次：</Col>
                <Col span="10" class="mb-20" v-if="beModifiedItem.indexOf('sweek') > -1">
                  <FormItem
                      :prop="'expTimeItems.' + expTimeIndex + '.sweek'"
                      :rules="ruleValidate.sweek">
                    <Select :enabledPreventOverflow="enabledPreventOverflow" v-model="timeItem.sweek" placeholder="第几周" filterable clearable>
                      <Option v-for="(n, index) in 21" :value="n" :key="index">{{ n }}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="2" class="pl-15 mb-20" v-if="beModifiedItem.indexOf('sdate') > -1">星期：</Col>
                <Col span="10" class="mb-20" v-if="beModifiedItem.indexOf('sdate') > -1">
                  <FormItem
                      :prop="'expTimeItems.' + expTimeIndex + '.sdate'"
                      :rules="ruleValidate.sdate">
                    <Select :enabledPreventOverflow="enabledPreventOverflow" v-model="timeItem.sdate" placeholder="星期几" filterable clearable>
                      <Option value=1>一</Option>
                      <Option value=2>二</Option>
                      <Option value=3>三</Option>
                      <Option value=4>四</Option>
                      <Option value=5>五</Option>
                      <Option value=6>六</Option>
                      <Option value=7>天</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="2" class="pl-15 mb-20" v-if="beModifiedItem.indexOf('section') > -1">节次：</Col>
                <Col span="10" class="mb-20" v-if="beModifiedItem.indexOf('section') > -1">
                  <FormItem
                      :prop="'expTimeItems.' + expTimeIndex + '.section'"
                      :rules="ruleValidate.section">
                    <Select :enabledPreventOverflow="enabledPreventOverflow" v-model="timeItem.section" multiple placeholder="第几节" filterable>
                      <Option v-for="n in 11" :value="n" :key="n">{{ n }}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="2" class="pl-15 pr-0 mb-20" v-if="beModifiedItem.indexOf('classroom') > -1">学院：</Col>
                <Col span="10" class="mb-20" v-if="beModifiedItem.indexOf('classroom') > -1">
                  <FormItem :prop="'expTimeItems.' + expTimeIndex + '.institute'"
                          :rules="ruleValidate.institute">
                    <Select v-model="timeItem.institute"
                            :enabledPreventOverflow="enabledPreventOverflow"
                            placeholder="请选择实验室所属学院"
                            filterable
                            :not-found-text="loading.institute ? '查询学院中，请稍等...' : '无可选学院'"
                            @on-change="onChangeLabInstitute(timeItem)"
                          >
                      <Option v-for="(option, index) in options.institute" :value="option" :key="index">{{ option }}</Option>
                    </Select>
                  </FormItem>
                </Col>
              </Row>
              <Row :gutter="20" type="flex" v-if="beModifiedItem.indexOf('classroom') > -1">
                <Col span="2" class="pl-15 pr-0">实验室：</Col>
                <Col span="18" style="width: 65%; padding-left: 10px; padding-right: 13px;">
                  <FormItem
                      :prop="'expTimeItems.' + expTimeIndex + '.classroom'"
                      :rules="ruleValidate.classroom">
                    <Select v-model="timeItem.classroom"
                            :enabledPreventOverflow="enabledPreventOverflow"
                            :placeholder="timeItem.institute ? '请选择实验室' : '请先选择学院'"
                            :disabled="!timeItem.institute"
                            filterable
                            clearable
                            multiple
                            :not-found-text="timeItem.labLoading ? '查询实验室中，请稍等...' : '无可选实验室'">
                      <Option
                        v-for="item in expForm.expTimeItems[expTimeIndex].labList"
                        :label="item.code"
                        :value="item.code"
                        :key="item.code"
                        :disabled="!('ACTIVATING'===item.status)">
                            <span>{{ item.code }}</span>
                            <span style="float:right;color:#ccc;margin-right: 15px;">{{ item.name + ' (' + item.capacity + '人)' }}</span>
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
          </fieldset>
      </Form>
      <div id="actions" class="text-center position-relative">
        <Poptip
            confirm
            title="确认批量修改信息吗？"
            word-wrap
            width="180"
            @on-ok="handleSave"
            class="text-left"
            :options="popperOpts">
            <Button type="success" :loading="loading.submit" class="mr-20">
              <span v-if="!loading.submit">提交表单</span>
              <span v-else>提交中...</span>
            </Button>
        </Poptip>
        <Poptip
            confirm
            title="数据将不可恢复，确定重置表单吗？"
            word-wrap
            width="180"
            @on-ok="handleReset"
            class="text-left"
            :options="popperOpts">
          <Button style="margin-left: 8px" :disabled="loading.submit">重置表单</Button>
        </Poptip>
      </div>
    </div>
    <div class="modal-container">
      <Modal v-model="modal.occupy.show" width="75" @on-ok="modal.occupy.show = false" footer-hide>
        <p slot="header" class="text-center" style="color:#f60;">
          <Icon type="ios-information-circle"></Icon>
          <span>{{ modal.occupy.title }}</span>
        </p>
        <div>
          <Table height="400" border size="small" :columns="occupyColumns" :data="occupyData.table" class="small-table"></Table>
        </div>
      </Modal>
      <Modal v-model="modal.detail.show" footer-hide width="90%" class="mb-50-modal">
        <p slot="header" class="text-center" style="color: #276f86;">{{ modal.detail.title }}</p>
        <applied-form-detail-table v-if="modal.detail.show" :code="modal.detail.code" :title="modal.detail.title"/>
      </Modal>
    </div>
  </div>
</template>
<script>

import { getInstituteList, getLabByTimes, getLabByInstitute, getFormDetailByCode, editApply } from '@/api/apply-form'
import { generateGuid } from '@/libs/tools'
import AppliedFormDetailTable from '_c/applied-form-detail-table/applied-form-detail-table'
export default {
  name: 'SaveCourseExpBatch',
  components: {
    'applied-form-detail-table': AppliedFormDetailTable
  },
  data () {
    return {
      loading: {
        institute: false,
        submit: false
      },
      options: {
        institute: []
      },
      expForm: {
        sid: 1,
        type: null,
        title: null,
        learntime: null,
        resources: null,
        system: null,
        software: null,
        expTimeItems: [
          {
            guid: generateGuid(),
            institute: null,
            sweek: null,
            sdate: null,
            section: [],
            classroom: [],
            labList: [],
            labLoading: false
          }
        ]
      },
      ruleValidate: {
        institute: [
          {required: true, message: '学院不能为空', trigger: 'change'}
        ],
        classroom: [
          {required: true, type: 'array', message: '实验室不能为空', trigger: 'change'}
        ],
        type: [
          {required: true, message: '实验类型不能为空', trigger: 'change'}
        ],
        title: [
          {required: true, message: '项目名称不能为空', trigger: 'blur'}
        ],
        sweek: [
          {required: true, type: 'number', message: '周次不能为空', trigger: 'change'}
        ],
        sdate: [
          {required: true, message: '星期不能为空', trigger: 'change'}
        ],
        section: [
          {required: true, type: 'array', message: '节次不能为空', trigger: 'change'}
        ],
        date: [
          {required: true, type: 'array', message: '实训时间不能为空', trigger: 'change'}
        ],
        learntime: [
          {required: true, type: 'number', message: '学时不能为空', trigger: 'change'},
          {required: true, type: 'number', message: '学时不能为空', trigger: 'blur'}
        ],
        resources: [
          {required: true, message: '耗材需求不能为空', trigger: 'blur'}
        ],
        system: [
          {required: true, message: '系统需求不能为空', trigger: 'blur'}
        ],
        software: [
          {required: true, message: '软件需求不能为空', trigger: 'blur'}
        ]
      },
      // 原申请表数据
      oriData: null,
      timer: null,
      // 被修改对象
      beModifiedObject: {},
      labelPosition: 'left',
      labelWidth: 100,
      // Select选择器的下拉列表是否吸附，默认为true，吸附
      enabledPreventOverflow: false,
      popperOpts: {
        modifiers: {
          preventOverflow: {
            // 边界元素: scrollParent, window, viewport or any DOM element. 默认iview默认window
            boundariesElement: 'scrollParent'
          }
        }
      },
      occupyColumns: [
        {
          title: '实验编号',
          key: 'expIndex',
          width: 60,
          align: 'center'
        },
        {
          title: '周次',
          key: 'weekNumber',
          sortable: true,
          width: 60,
          align: 'center'
        },
        {
          title: '星期',
          key: 'week',
          sortable: true,
          width: 60,
          align: 'center'
        },
        {
          title: '节次',
          key: 'section',
          sortable: true,
          width: 60,
          align: 'center'
        },
        {
          title: '实验室',
          key: 'code',
          minwidth: 150,
          align: 'center'
        },
        {
          title: '已申请的申请表相关信息',
          align: 'center',
          children: [
            {
              title: '教师姓名',
              key: 'teacherName',
              align: 'center',
              width: 60
            },
            {
              title: '课程名称',
              key: 'courseName',
              align: 'center'
            },
            {
              title: '实验编号',
              key: 'experimentNumber',
              align: 'center',
              width: 60
            },
            {
              title: '实验名称',
              key: 'experimentName',
              align: 'center',
              minWidth: 120
            },
            {
              title: '操作',
              key: 'action',
              align: 'center',
              width: 80,
              render: (h, params) => {
                return h('div', [
                  h('Button', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    on: {
                      click: () => {
                        this.openDetail(params)
                      }
                    }
                  }, '查看详情')
                ])
              }
            }
          ]
        }
      ],
      occupyData: {
        table: []
      },
      modal: {
        occupy: {
          show: false,
          title: '抱歉，提交失败，实验室使用时间冲突'
        },
        detail: {
          show: false,
          title: '',
          code: ''
        }
      }
    }
  },
  props: {
    fieldsetTitle: {
      type: String,
      default: '实验基本信息'
    },
    app_code: {
      type: String,
      default: null
    },
    selection: {
      type: Array,
      default: null
    },
    beModifiedItem: {
      type: Array,
      default: null
    }
  },
  methods: {
    // 获取学院列表
    async getInstituteOptions () {
      this.loading.institute = true
      let options = []
      try {
        let res = await getInstituteList()
        res = res.data
        if (res.code && res.data.length > 0) {
          options = res.data
        } else {
          this.$Notice.error({
            title: res.code ? '暂无学院' : '获取学院列表失败',
            desc: res.code ? '暂无可选学院，请刷新后重试' : res.info
          })
          options = []
        }
      } catch (error) {
        console.log(error)
        this.$Notice.error({
          title: '获取学院列表失败',
          desc: error
        })
        options = []
      }
      this.loading.institute = false
      return options
    },
    // 获取实验室列表
    async getLabOptions (isByTime, requestInstitute, requestTime) {
      let options = []
      try {
        let res = isByTime ? await getLabByTimes(requestTime, requestInstitute, this.editSingle ? this.app_code : '') : await getLabByInstitute(requestInstitute)
        res = res.data
        if (res.code && res.data.length > 0) {
          options = res.data
        } else {
          this.$Notice.error({
            title: res.code ? '暂无实验室' : '获取实验室列表失败',
            desc: res.code ? '暂无可选实验室，请刷新后重试' : res.info
          })
          options = []
        }
      } catch (error) {
        console.log(error)
        this.$Notice.error({
          title: '获取实验室列表失败',
          desc: error
        })
        options = []
      }
      return options
    },
    // 新增实验时间
    addTime () {
      this.expForm.expTimeItems.push({
        guid: generateGuid(),
        institute: this.expForm.expTimeItems[0].institute,
        sweek: null,
        sdate: null,
        section: [],
        classroom: [],
        labList: [],
        labLoading: false
      })
    },
    // 删除实验时间
    removeTime (item, index) {
      if (this.expForm.expTimeItems.indexOf(item) !== -1) {
        this.expForm.expTimeItems.splice(index, 1)
      }
    },
    // 改变实验室学院的回调函数
    async onChangeLabInstitute (timeItem) {
      if (timeItem.institute) {
        timeItem.labLoading = true
        timeItem.labList = await this.getLabOptions(false, timeItem.institute, null)
        timeItem.labLoading = false
      }
    },
    // 通过appCode获取历史申请表的详细信息
    async getPastFormByCode (code) {
      try {
        let res = await getFormDetailByCode(code)
        res = res.data
        if (res.code) {
          this.oriData = this.transferDetail(res.data)
        } else {
          this.$emit('failFillFrom', '抱歉，获取原申请表信息失败，请刷新后重试。' + res.info)
        }
      } catch (error) {
        this.$emit('failFillFrom', '抱歉，获取原申请表信息失败，请刷新后重试。' + error)
        console.log(error)
      }
    },
    // 通过从后台获取的数据填充到当前表单中
    async fillFormByData (data) {
      this.isFilledForming = true
      let expItem = null
      for (let i = 0; i < data.expBaseInfoItems.length; i++) {
        const item = data.expBaseInfoItems[i]
        item.learntime = item.plan_hours
        let tempMap = new Map()
        item.expTimeItems = []
        delete item.plan_hours
        delete item.actual_hours
        delete item.expTimeItemsTrain
        // 遍历各个子实验时间，根据index合并为原始数值
        item.expTimeItemsCourse.forEach(c => {
          if (!tempMap.has(c.index)) {
            tempMap.set(c.index, {
              institute: c.classroom.institute,
              sweek: c.expItemTime.sweek,
              sdate: c.expItemTime.sdate + '',
              section: new Set().add(c.expItemTime.section),
              classroom: new Set().add(this.editSingle ? c.classroom.code : '')
            })
          } else {
            tempMap.get(c.index).section.add(c.expItemTime.section)
            tempMap.get(c.index).classroom.add(this.editSingle ? c.classroom.code : '')
          }
        })
        // 把 子实验时间 expTimeItemsCourse 转换为数组
        item.expTimeItemsCourse = Array.from(tempMap)
        // 遍历一次转换的数组，获取各个实验的可用实验室
        for (let j = 0; j < item.expTimeItemsCourse.length; j++) {
          const c = item.expTimeItemsCourse[j]
          c[1].section = Array.from(c[1].section)
          c[1].guid = generateGuid()
          let time = {
            'sweek': c[1].sweek,
            'sdate': parseInt(c[1].sdate),
            'section': c[1].section
          }
          let requestInstitute = c[1].institute
          if (item.sid === this.sid) {
            try {
              let res = await getLabByTimes(time, requestInstitute, this.editSingle ? data.app_code : '')
              res = res.data
              if (res.code) {
                if (res.data.length > 0) {
                  c[1].labList = res.data.map(item => {
                    return {
                      code: item.code,
                      name: item.name,
                      capacity: item.capacity,
                      status: item.status
                    }
                  })
                  c[1].classroom = Array.from(c[1].classroom)
                  item.expTimeItems.push(c[1])
                } else {
                  this.$Notice.error({
                    title: '暂无实验室列表',
                    desc: '抱歉，该时间下暂无空余实验室，请选择其他实验时间'
                  })
                }
              } else {
                this.$Notice.error({
                  title: '获取实验室列表失败',
                  desc: res.info
                })
                c[1].labList = []
                c[1].classroom = Array.from(c[1].classroom)
                item.expTimeItems.push(c[1])
              }
            } catch (error) {
              this.$Spin.hide()
              console.log(error)
              c[1].labList = []
              c[1].classroom = Array.from(c[1].classroom)
              item.expTimeItems.push(c[1])
            }
          }
          c[1].labLoading = false
        }
        delete item.expTimeItemsCourse
        if (item.sid === this.sid) {
          expItem = item
        }
      }
      if (expItem) {
        this.$nextTick(() => {
          this.oriData = JSON.parse(JSON.stringify(expItem))
          this.expForm = expItem
          setTimeout(() => {
            this.isFilledFormByData = true
          }, 1000)
          this.$Spin.hide()
        })
      } else {
        this.$Notice.error({
          title: '获取子实验失败',
          desc: '抱歉，该子实验已经不存在，请刷新后重试'
        })
      }
      this.$Spin.hide()
    },
    // 保存 修改的单个实验
    handleSave () {
      this.$refs['expForm'].validate(async (valid) => {
        if (valid) {
          this.loading.submit = true
          this.showSpinWithTip('提交表单中，请稍等...')
          try {
            let data = this.handleSaveData()
            let response = await editApply(JSON.stringify(data))
            let res = response.data
            if (res.code) {
              this.$emit('saveSuccess', true, false)
            } else {
              if (this.getElClass(res.data) === 'Array' && res.data.length > 0) {
                this.occupyData.table = []
                for (let i = 0; i < res.data.length; i++) {
                  for (let j = 0; j < res.data[i].length; j++) {
                    let item = {}
                    item.expIndex = i + 1
                    item.weekNumber = res.data[i][j].usageTime.sweek
                    item.week = res.data[i][j].usageTime.sdate
                    item.section = res.data[i][j].usageTime.section
                    item.code = res.data[i][j].labCode
                    item.teacherName = res.data[i][j].teacherName
                    item.courseName = res.data[i][j].courseName
                    item.experimentNumber = res.data[i][j].experimentNumber
                    item.experimentName = res.data[i][j].experimentName
                    item.appCode = res.data[i][j].app_code
                    let children = this.occupyColumns[this.occupyColumns.length - 1].children
                    if (item.appCode === '0' && children && children[children.length - 1].key === 'action') {
                      children.pop()
                    } else if (item.appCode !== '0' && children && children[children.length - 1].key !== 'action') {
                      children.push({
                        title: '操作',
                        align: 'center',
                        key: 'action',
                        width: 80,
                        render: (h, params) => {
                          return h('div', [
                            h('Button', {
                              props: {
                                type: 'primary',
                                size: 'small'
                              },
                              on: {
                                click: () => {
                                  this.openDetail(params)
                                }
                              }
                            }, '查看详情')
                          ])
                        }
                      })
                    }
                    this.occupyData.table.push(item)
                  }
                }
                this.modal.occupy = {
                  'show': true,
                  'title': res.info ? res.info : '抱歉，实验室使用时间冲突，请重新选择'
                }
              } else {
                this.$Notice.error({
                  title: '提交失败',
                  desc: (this.editSingle ? '修改单个实验信息失败，' : '新增单个实验失败，') + res.info
                })
              }
            }
          } catch (error) {
            console.log(error)
            this.$Notice.error({
              title: '提交失败',
              desc: (this.editSingle ? '修改单个实验信息失败，' : '新增单个实验失败，') + error
            })
          }
          this.$Spin.hide()
        } else {
          this.$Notice.error({
            title: '提交失败',
            desc: '抱歉，无法提交，请先完善表单信息再提交。'
          })
        }
      })
      this.loading.submit = false
    },
    handleSaveData () {
      let tempData = JSON.parse(JSON.stringify(this.expForm, function (key, value) {
        if (key === 'sid' || key === 'labList' || key === 'labLoading' || key === 'guid' || !value || ((key === 'classroom' || key === 'section') && value.length <= 0)) {
          return undefined
        } else {
          return value
        }
      }))
      // 提取需要修改的值
      let data = {}
      data.expTimeItems = tempData.expTimeItems[0]
      delete tempData.expTimeItems
      data.base = {...tempData}
      // 复制原始数据
      let temp = {...this.oriData}
      temp.expBaseInfoItems.forEach(item => {
        [...item.expTimeItems] = item.expTimeItems
        if (this.beModifiedObject.sids.indexOf(item.sid) >= 0) {
          // 临时子实验时间变量
          let [...tempTimes] = item.expTimeItems
          delete item.expTimeItems
          // 有选中上半部分的时候才修改上半部分
          if (this.beModifiedItem.some(item => { return ['type', 'planHours', 'title', 'system', 'software', 'resources', 'classroom'].indexOf(item) > -1 })) {
            item = Object.assign(item, data.base)
          }
          // 有选中时间和实验室部分才修改
          if (this.beModifiedItem.some(item => { return ['sweek', 'sdate', 'section', 'classroom'].indexOf(item) > -1 })) {
            this.beModifiedObject.objs[item.sid].forEach(tIndex => {
              if (tempTimes[tIndex]) {
                tempTimes[tIndex] = Object.assign(tempTimes[tIndex], data.expTimeItems)
              }
            })
          }
          item.expTimeItems = tempTimes
        }
      })
      return temp
    },
    // 重置表单
    handleReset () {
      this.$refs['expForm'].resetFields()
      this.resetFormData()
    },
    resetFormData () {
      let notData = {
        sid: 1,
        type: '',
        title: null,
        learntime: null,
        resources: null,
        system: null,
        software: null,
        expTimeItems: [
          {
            guid: generateGuid(),
            institute: null,
            sweek: null,
            sdate: null,
            section: [],
            classroom: [],
            labList: [],
            labLoading: false
          }
        ]
      }
      this.expForm = JSON.parse(JSON.stringify(notData))
    },
    getBeModifiedObject (selection) {
      let bmo = {
        sids: [],
        objs: []
      }
      let tempMap = new Map()
      selection.forEach(item => {
        if (tempMap.has(item.sid)) {
          tempMap.get(item.sid).push(item.tIndex)
        } else {
          tempMap.set(item.sid, [item.tIndex])
        }
        if (bmo.sids.indexOf(item.sid) < 0) {
          bmo.sids.push(item.sid)
        }
      })
      tempMap.forEach((value, key) => {
        bmo.objs[key] = value
      })
      return bmo
    },
    // 展开申请表详细信息
    openDetail (params) {
      this.modal.detail = {
        show: true,
        title: params.row.teacherName + '老师的' + '《' + params.row.courseName + '》课程相关的实验课信息登记表',
        code: params.row.appCode || ''
      }
    },
    // 显示带文字提示的Spin
    showSpinWithTip (tip) {
      this.$Spin.show({
        render: h => {
          return h('div', { class: 'ivu-spin-large' }, [
            h('span', {
              class: 'ivu-spin-dot',
              style: {
                display: 'inline-block'
              }
            }),
            h('div', tip)
          ])
        }
      })
    },
    getElClass (o) {
      if (o === null) return 'Null'
      if (o === undefined) return 'undefined'
      return Object.prototype.toString.call(o).slice(8, -1)
    },
    transferDetail (detail) {
      let data = {...detail}
      delete data.course_name
      delete data.stu_num
      delete data.course_type
      for (let i = 0; i < data.expBaseInfoItems.length; i++) {
        const item = data.expBaseInfoItems[i]
        item.learntime = item.plan_hours
        let tempMap = new Map()
        item.expTimeItems = []
        delete item.plan_hours
        delete item.actual_hours
        delete item.expTimeItemsTrain
        // 遍历各个子实验时间，根据index合并为原始数值
        item.expTimeItemsCourse.forEach(c => {
          if (!tempMap.has(c.index)) {
            tempMap.set(c.index, {
              institute: c.classroom.institute,
              sweek: c.expItemTime.sweek,
              sdate: c.expItemTime.sdate + '',
              section: new Set().add(c.expItemTime.section),
              classroom: new Set().add(c.classroom.code)
            })
          } else {
            tempMap.get(c.index).section.add(c.expItemTime.section)
            tempMap.get(c.index).classroom.add(c.classroom.code)
          }
        })
        // 把 子实验时间 expTimeItemsCourse 转换为数组
        item.expTimeItemsCourse = Array.from(tempMap)
        // 遍历一次转换的数组，获取各个实验的可用实验室
        for (let j = 0; j < item.expTimeItemsCourse.length; j++) {
          const c = item.expTimeItemsCourse[j]
          c[1].section = Array.from(c[1].section)
          c[1].classroom = Array.from(c[1].classroom)
          item.expTimeItems.push(c[1])
        }
        delete item.expTimeItemsCourse
      }
      return data
    }
  },
  created: async function () {
    this.showSpinWithTip('加载中，请稍等...')
    if (this.beModifiedItem.indexOf('classroom') > -1) {
      this.options.institute = await this.getInstituteOptions()
    }
    await this.getPastFormByCode(this.app_code)
    this.beModifiedObject = this.getBeModifiedObject(this.selection)
    this.$nextTick(() => {
      this.$Spin.hide()
    })
  },
  mounted: function () {
    // 全局配置Notice组件的属性
    this.$Notice.config({
      top: window.innerHeight / 3
    })
  },
  beforeDestroy () {
    this.$Notice.destroy()
    this.$Modal.remove()
  }
}
</script>
<style lang="less" scoped>
  .form-container {
    .ivu-divider-dashed {
      border-color: #ccc;
      padding-top: 20px;
    }
  }
</style>
